package com.hmdp.service.impl;

import com.hmdp.config.RedissonConfig;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.ILockImpl;
import com.hmdp.utils.LoginInterceptor;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService iSeckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private IVoucherOrderService proxy;

    /**
     * 创建阻塞队列
     */
    private BlockingQueue<VoucherOrder> orderQueue = new ArrayBlockingQueue<>(1024 * 1024);

    /**
     * 创建线程池
     */
    private static final ExecutorService executorService = Executors.newSingleThreadExecutor();

    /**
     * 代表类初始化完毕加载
     */
    @PostConstruct
    private void init(){
        executorService.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            try {
                while (true) {
                    //获取队列的订单信息
                    VoucherOrder voucherOrder = orderQueue.take();
                    //创建订单
                    handleVoucherOrder(voucherOrder);
                }

            } catch (Exception e) {
                log.error("处理订单异常",e);
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        //获取锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //判断锁是否成功
        if(!lock.tryLock()){
            //获取锁失败
            log.error("不允许重复下单");
            return;
        }
        try {
            proxy.createOrderVoucherHandler(voucherOrder);
        }finally {
            //释放锁
            lock.unlock();
        }

    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        //执行lua脚本
        UserDTO user = UserHolder.getUser();
        Long execute = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                user.getId().toString());
        if(execute.intValue() != 0){
            return Result.fail(execute == 1 ? "库存不足" : "重复下单");
        }

        //生成唯一订单号
        long orderId = redisIdWorker.nexId("order");
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(user.getId());
        voucherOrder.setVoucherId(voucherId);

        //保存在阻塞队列
        orderQueue.add(voucherOrder);

        //获取代理对象（事务）
        proxy = (IVoucherOrderService)AopContext.currentProxy();

        return Result.ok(orderId);
    }

    /**
     * 优惠券秒杀功能 @Transactional：添加事务，多表，一个失败则执行失败
     * @param voucherId 商品id
     * @return 是否成功
     */

    /*@Override
    public Result seckillVoucher(Long voucherId) {
        //查询优惠券
        SeckillVoucher seckillVoucher = iSeckillVoucherService.getById(voucherId);
        //判断活动是否开始
        if(seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀活动尚未开始！");
        }
        if(seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀活动已经结束！");
        }
        //判断库存是否充足
        if(seckillVoucher.getStock() < 1){
            return Result.fail("库存不足！");
        }
        UserDTO user = UserHolder.getUser();
        //实现一人一单 集群版
        //ILockImpl lock = new ILockImpl("order:" + user.getId(), stringRedisTemplate);
        RLock lock = redissonClient.getLock("lock:order:" + user.getId());
        //判断锁是否成功
        if(!lock.tryLock()){
            //获取锁失败，返回错误或重试
            return Result.fail("不允许重复下单！");
        }
        try {
            //获取代理对象（事务）
            IVoucherOrderService proxy = (IVoucherOrderService)AopContext.currentProxy();
            return proxy.createOrderVoucher(voucherId);
        }finally {
            //释放锁
            lock.unlock();
        }
        //实现一人一单 单机版
        //synchronized (user.getId().toString().intern()){
            //获取代理对象（事务）
            //IVoucherOrderService proxy = (IVoucherOrderService)AopContext.currentProxy();
           // return proxy.createOrderVoucher(voucherId);
        //}

    }*/

    @Transactional
    public Result createOrderVoucher(Long voucherId) {
        UserDTO user = UserHolder.getUser();
        //一人一单判断
        int count = query().eq("user_id", user.getId()).eq("voucher_id", voucherId).count();
        if(count > 0){
            return Result.fail("该用户已经购买过，无法继续购买！");
        }
        //扣减库存
        iSeckillVoucherService.update().setSql("stock = stock - 1")
                //乐观锁CAS:避免超卖问题，问题解决，但是成功率极低
                //.eq("stock", seckillVoucher.getStock())
                .gt("stock",0)
                .eq("voucher_id", voucherId).update();

        //创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = redisIdWorker.nexId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(user.getId());
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
        //返回订单id
        return Result.ok(orderId);
    }

    @Override
    public void createOrderVoucherHandler(VoucherOrder voucherOrder) {
        //一人一单判断
        int count = query().eq("user_id", voucherOrder.getId()).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if(count > 0){
            log.error("用户已经购买过一次");
            return;
        }
        //扣减库存
        boolean update = iSeckillVoucherService.update().setSql("stock = stock - 1")
                .gt("stock", 0)
                .eq("voucher_id", voucherOrder.getVoucherId()).update();

        if(!update){
            log.error("库存不足");
            return;
        }

        //创建订单
        save(voucherOrder);
    }
}
